package com.guosheng.test20181129;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.util.List;

@XmlRootElement(name="list")
public class StudentList {

    private List<Student> students;

    private Grade grade;

    @XmlElement(name="grade")
    public Grade getGrade() {
        return grade;
    }

    public void setGrade(Grade grade) {
        this.grade = grade;
    }

    @XmlElement(name="student")
    public List<Student> getStudents() {
        return students;
    }

    public void setStudents(List<Student> students) {
        this.students = students;
    }

    class MarshallerListener extends Marshaller.Listener{
        public static final String BLANK_CHAR = "";
        @Override
        public void beforeMarshal(Object source) {
            super.beforeMarshal(source);
            Field[] fields = source.getClass().getDeclaredFields();
            for (Field f : fields) {
                f.setAccessible(true);
                try {
                    if (f.getType() == String.class && f.get(source) == null) {
                        f.set(source, BLANK_CHAR);
                    }
                    if(f.getType() == Grade.class && f.get(source) == null){
                        Grade grade = new Grade();
                        Field[] fieldg = grade.getClass().getDeclaredFields();
                        for(Field fg :fieldg){
                            fg.setAccessible(true);
                            if (fg.getType() == String.class && fg.get(grade) == null) {
                                fg.set(source, BLANK_CHAR);
                            }
                        }
                        f.set(source,grade);
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

   public static String userconvertToXml(Object obj, Class<?> load){
        try {
            JAXBContext context = JAXBContext.newInstance(load);
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
            marshaller.setProperty(Marshaller.JAXB_ENCODING,"utf-8");
            StudentList.MarshallerListener marlistener=new StudentList().new MarshallerListener();
            marshaller.setListener(marlistener);
            StringWriter writer = new StringWriter();
            marshaller.marshal(obj, writer);
            return writer.toString();
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return null;
    }


}
